//
//  HJPostContentController.m
//  KaiChat
//
//  Created by lx on 2024/3/27.
//

#import "HJPostContentController.h"
#import "HJRecommendInformationCell.h"
#import "HJInformationFollowCell.h"
#import "HJInformationPresent.h"
#import "HJRefreshFooter.h"
#import "HJRefreshHeader.h"
#import "HJFlutterController.h"
#import "TJEmptyDataHandler.h"
#import "HJPhotoBrowser.h"
#import "HJShareController.h"
#import "HJVideoPlayController.h"
#import "HJPopMenuController.h"
#import "HJUserHomePageController.h"
#import "HJFlutteAlertController.h"

@interface HJPostContentController ()<HJInformationCellDelegate>

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;

@end

@implementation HJPostContentController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageIndex = 1;
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.1)];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    [self.tableView registerClass:HJRecommendInformationCell.class forCellReuseIdentifier:@"HJRecommendInformationCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView setSectionIndexColor:UIColor.tj_9B9B9BColor];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    [self loadNewData];
    
    self.tableView.mj_footer = [HJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer.hidden = YES;
    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleFlutterPageOperateNotification:) name:flutterPageOperateNotification object:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJRecommendInformationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJRecommendInformationCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.layout = self.datas[indexPath.row];;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJInformationLayout *layout = self.datas[indexPath.row];
    HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageNews];
    flutterController.arguments = @{
        @"type": @(1),
        @"id": layout.model.informationId
    };
    [self.navigationController pushViewController:flutterController];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJInformationLayout *model = self.datas[indexPath.row];
    return model.height;
}

- (void)informationCellDidClickFoldButton:(HJInformationFollowCell *)cell foldButton:(UIButton *)foldButton {
    HJInformationLayout *layout = cell.layout;
    layout.isFold = !layout.isFold;
    [layout calculateLayout];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [UIView setAnimationsEnabled:NO];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [UIView setAnimationsEnabled:YES];
}

- (void)informationCellDidClickImageView:(HJRecommendInformationCell *)cell imageView:(UIImageView *)imageView index:(NSInteger)index {
    
    if (cell.layout.isVideo) {
        HJVideoPlayController *videoPlayController = [[HJVideoPlayController alloc] init];
        videoPlayController.url = cell.layout.mediaDatas.firstObject;
        [self presentViewController:videoPlayController animated:YES completion:nil];
        return;
    }
    
    NSMutableArray *Marr = [NSMutableArray array];
    [cell.layout.model.images enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        HJPhotoItem *item = [[HJPhotoItem alloc] init];
        item.thumbUrl = obj;
        item.originalUrl = obj;
        if (idx == index) {
            item.sourceView = imageView;
            item.thumbImage = imageView.image;
        }
        [Marr addObject:item];
    }];
    HJPhotoBrowser *browser = [HJPhotoBrowser browserWithPhotoItems:Marr selectedIndex:index];
    [browser showFromViewController:self];
}

- (void)informationCellDidClickTapAvatarImageView:(HJRecommendInformationCell *)cell {
    HJInformationModel *model = cell.layout.model;
    HJUserHomePageController *userHomePageController = [[HJUserHomePageController alloc] init];
    userHomePageController.userId = model.userId;
    userHomePageController.nickName = model.nickname;
    [[HJTools currentNavController] pushViewController:userHomePageController];
}

- (void)informationCellDidClickMoreButton:(HJRecommendInformationCell *)cell button:(UIButton *)button {
    
    HJInformationModel *model = cell.layout.model;
    
    NSMutableArray *types = [NSMutableArray array];
    if (model.isSelf) {
        [types addObject:@(HJPopMenuTypeNewsDelete)];
    } else {
        if (model.is_follow) {
            [types addObject:@(HJPopMenuTypeNewsUnFollow)];
        } else {
            [types addObject:@(HJPopMenuTypeNewsFollow)];
        }
        [types addObject:@(HJPopMenuTypeNewsHiden)];
    }
    
    HJPopMenuController *popMenuController = [[HJPopMenuController alloc] initWithTypes:types];
    popMenuController.controllerName = NSStringFromClass(self.class);
    popMenuController.sourceRect = [button.superview convertRect:button.frame toView:getMainWindow()];
    [popMenuController showInController:self];
    TJWeakify(self)
    [popMenuController setDidSelectItemBlock:^(HJPopMenuType type) {
        if (type == HJPopMenuTypeNewsDelete) {
            [HJInformationPresent deletePostDataWithNewsId:model.informationId complete:^(NSError * _Nullable error) {
                if (!error) {
                    [weakself.datas removeObject:cell.layout];
                    if (weakself.datas.count == 0) {
                        [weakself.tableView reloadData];
                    } else {
                        NSIndexPath *indexPath = [weakself.tableView indexPathForCell:cell];
                        [weakself.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }
            }];
            return;
        }
        
        if (type == HJPopMenuTypeNewsFollow || type == HJPopMenuTypeNewsUnFollow) {
            [HJInformationPresent followUser:model.userId complete:^(NSError * _Nullable error) {
                if (!error) {
                    model.is_follow = !model.is_follow;
                    cell.layout = cell.layout;
                    
                    if (cell.layout.model.is_follow) {
                        [HJHUD showSucceedMessage:@"Follow the success"];
                    } else {
                        [HJHUD showMessage:@"unfollow"];
                    }
                    
                    //修改所有数据源的关注
                    for (HJInformationLayout *obj in self.datas) {
                        if ([obj.model.userId isEqualToString:model.userId]) {
                            obj.model.is_follow = model.is_follow;
                        }
                    }
                }
            }];
            return;
        }
        
        if (type == HJPopMenuTypeNewsHiden) {
            [HJInformationPresent hidePostDataWithNewsId:model.informationId complete:^(NSError * _Nullable error) {
                if (!error) {
                    [weakself.datas removeObject:cell.layout];
                    if (weakself.datas.count == 0) {
                        [weakself.tableView reloadData];
                    } else {
                        NSIndexPath *indexPath = [weakself.tableView indexPathForCell:cell];
                        [weakself.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }
            }];
            return;
        }
    }];
}


- (void)informationCellDidClickOperateViewButton:(HJRecommendInformationCell *)cell type:(HJInformationOperateType)type button:(UIButton *)button {
    
    HJInformationLayout *layout = cell.layout;
    
    if (type == HJInformationOperateShare) {
        HJShareController *shareController = [[HJShareController alloc] init];
        shareController.objects = @[[NSString stringWithFormat:@"%@?articleType=%@&userId=%@&articleId=%@", getNewsShareUrl(), @(self.type), HJUserInfo.userId, layout.model.informationId]];
        [shareController setSucceedBlock:^{
            [HJInformationPresent statisticsUserShareDataWithType:1 newsId:layout.model.informationId complete:^(NSError * _Nullable error) {
                if (!error) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:flutterPageOperateNotification object:@{
                        @"type": @(1),
                        @"id": layout.model.informationId,
                        @"action": @"share"
                    }];
                }
            }];
        }];
        [HJTools.currentViewController presentViewController:shareController animated:YES completion:nil];
        return;
    }
    
    if (type == HJInformationOperateLike) {
        if (layout.isSendLikeRequest) {
            return;
        }

        BOOL isLike = !layout.model.is_like;
        layout.isSendLikeRequest = YES;
        [HJInformationPresent newsLikeWithType:self.type newsId:layout.model.informationId isLike:isLike complete:^(NSError * _Nullable error) {
            layout.isSendLikeRequest = NO;
            if (!error) {
                if (isLike) {
                    layout.model.like++;
                } else {
                    layout.model.like--;
                }
                layout.model.is_like = isLike;
                cell.layout = layout;
            }
        }];
        return;
    }
    
    
    if (type == HJInformationOperateComment) {
        HJFlutteAlertController *flutterController = [[HJFlutteAlertController alloc] initWithName:HJFlutterPageNewsComment];
        flutterController.arguments = @{
            @"type": @(1),
            @"id": layout.model.informationId,
            @"toName": layout.model.nickname ?: @""
        };
        [self presentViewController:flutterController animated:NO completion:nil];
        return;
    }
    
    HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageNews];
    flutterController.arguments = @{
        @"type": @(1),
        @"id": layout.model.informationId,
    };
    [self.navigationController pushViewController:flutterController];
}

- (void)handleFlutterPageOperateNotification:(NSNotification *)not {
    
    NSDictionary *arguments = not.object;
    NSInteger type = [arguments[@"type"] integerValue];

    NSString *informationId = arguments[@"id"];
    NSString *action = arguments[@"action"];
    
    if ([action isEqualToString:@"share"] || [action isEqualToString:@"forward"]) {
        [self.datas enumerateObjectsUsingBlock:^(HJInformationLayout *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.model.informationId isEqualToString:informationId]) {
                obj.model.share++;
                *stop = YES;
            }
        }];
        [self reloadCell:informationId];
        return;
    }
    
    if ([action isEqualToString:@"views"]) {
        [self.datas enumerateObjectsUsingBlock:^(HJInformationLayout *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.model.informationId isEqualToString:informationId]) {
                obj.model.views++;
                *stop = YES;
            }
        }];
        [self reloadCell:informationId];
        return;
    }
    
    if ([action isEqualToString:@"comment"]) {
        [self.datas enumerateObjectsUsingBlock:^(HJInformationLayout *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.model.informationId isEqualToString:informationId]) {
                obj.model.comment++;
                *stop = YES;
            }
        }];
        [self reloadCell:informationId];
        return;
    }
    
    
    if ([action isEqualToString:@"like"]) {
        [HJInformationPresent loadNewsStatisticsDataWithType:self.type newsId:informationId complete:^(NSDictionary * _Nullable data) {
            [self.datas enumerateObjectsUsingBlock:^(HJInformationLayout *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.model.informationId isEqualToString:informationId]) {
                    obj.model.like = [data[@"likes"] integerValue];
                    obj.model.is_like = [data[@"like_status"] intValue] == 0;
                    *stop = YES;
                }
            }];
            [self reloadCell:informationId];
        }];
        return;
    }
    
}

- (void)reloadCell:(NSString *)informationId {
    [self.tableView.visibleCells enumerateObjectsUsingBlock:^(__kindof HJRecommendInformationCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.layout.model.informationId isEqualToString:informationId]) {
            obj.layout = obj.layout;
            *stop = YES;
        }
    }];
    
}
- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}


- (void)loadNewData {
    
    self.pageIndex = 1;
    [self.tableView.mj_footer resetNoMoreData];
    
    [HJInformationPresent loadHomeNewsListWithUserId:self.userId type:self.type pageIndex:self.pageIndex complete:^(NSInteger totalCount, NSArray<HJInformationModel *> * _Nullable news, NSError * _Nullable error) {
        
        [self.datas removeAllObjects];
        [self.tableView.mj_header endRefreshing];
        self.pageIndex = 2;
        self.emptyDataHandler.canDisplay = YES;
        
        if (news.count) {
            self.tableView.mj_footer.hidden = NO;
        }
        
        if (news.count <= totalCount) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        for (HJInformationModel *model in news) {
            [self.datas addObject:[HJInformationLayout layoutWithModel:model]];
        }
        
        [self.tableView reloadData];
    }];
    
}

- (void)loadMoreData {
    
    [HJInformationPresent loadHomeNewsListWithUserId:self.userId type:self.type pageIndex:self.pageIndex complete:^(NSInteger totalCount, NSArray<HJInformationModel *> * _Nullable news, NSError * _Nullable error) {
        
        [self.tableView.mj_footer endRefreshing];
        
        if (error) {
            return;
        }
        
        self.pageIndex++;
        
        if (news.count) {
            NSMutableArray *datas = [NSMutableArray array];
            for (HJInformationModel *model in news) {
                [datas addObject:[HJInformationLayout layoutWithModel:model]];
            }
            [self.datas addObjectsFromArray:datas];
        }
        
        if (self.datas.count <= totalCount) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.tableView reloadData];
    }];
}

- (BOOL)hiddenNavigationBar {
    return YES;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
